package com.petruisfan.banimei;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class RecordsDbAdapter {
	private static final String TAG = RecordsDbAdapter.class.getSimpleName();
	
	private static final String KEY_ROWID = "_id";
	static final String KEY_TITLE = "Item";
	static final String KEY_VALUE = "Value";
	private static final String KEY_DATE = "Date";
	
    private static final String DATABASE_NAME = "banimei";
    private static final String DATABASE_TABLE = "records";
    private static final int DATABASE_VERSION = 1;
    
    private static final String DATABASE_CREATE =
            "create table " + DATABASE_TABLE + " (" + KEY_ROWID + " integer primary key autoincrement, " + 
            KEY_TITLE + " text not null, " +
            KEY_VALUE + " real not null, " +
            KEY_DATE + " text not null); ";
    
    private static Context mCtx = null;
    private static DatabaseHelper mDbHelper;
    private static SQLiteDatabase mDb;

    
    public RecordsDbAdapter(Context context) {
    	mCtx = context;
    }

    public RecordsDbAdapter() {
    }

    
    /**
     * Open the notes database. If it cannot be opened, try to create a new
     * instance of the database.
     * 
     * @return	this
     * @throws SQLException
     */
    public RecordsDbAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        mDbHelper.close();
    }
    
    /**
     * TODO: bad programming patern?
     * Be carefull how you use this!!!
     * @return database adapter that is already initialized, and opened!!!
     */
    public RecordsDbAdapter getInstance() {
    	return this;
    }
    
    public long addRecord(String title, String value, String currentDate) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_TITLE, title);
        initialValues.put(KEY_VALUE, value);
        initialValues.put(KEY_DATE, currentDate);

        return mDb.insert(DATABASE_TABLE, null, initialValues);
    }
    
    public Cursor fetchAllRecords() {
        return mDb.query(DATABASE_TABLE, 
        		new String[] {KEY_ROWID, KEY_TITLE, KEY_VALUE, KEY_DATE}, 
        		null, 
        		null, 
        		null, 
        		null, 
        		null);
    }    
    
    /**
     * @return	The sum of all values inserted.
     */
    public String getSum() {
    	Cursor cursor = mDb.rawQuery("select sum(" + KEY_VALUE + ") from " + DATABASE_TABLE +";" , null);
    	cursor.moveToFirst();
    	String result = cursor.getFloat(0) + "";
    	return result;
    }
    
    /**
     * Delete table records.
     */
    public void dropTable() {
    	mDb.execSQL("delete from " + DATABASE_TABLE + " where " + KEY_ROWID + " > 0");
    }
    
    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion);
//            db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
//            onCreate(db);
        }
    }

	public String[] getRecordNames() {
		Cursor cursor = mDb.rawQuery("select " + KEY_TITLE + " from " + DATABASE_TABLE +";" , null);
    	
		cursor.moveToLast();
		int records = cursor.getPosition();
		if (records <= 0) {
			return new String[0];
		}

		String[] result = new String[records];
		
		cursor.moveToFirst();
    	for (int i=0; i<records; i++) {
    		result[i] = cursor.getString(0);
    		cursor.moveToNext();
    	}
    	
		return result;
	}

	public void deleteRecord(int id) {
		String query = "Delete from " + DATABASE_TABLE + " where " + KEY_ROWID + " = " + id;
//		Log.d(TAG, query);				
		mDb.execSQL(query);
	}
}
